<?php
/**
 * User: shaopu
 * Date: 2020-05-7
 * Time: 18:25
 */
namespace Buu\Modules\HaohaoceManager\Controllers;



use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Widgets\Collapse;
use Encore\Admin\Layout\Row;



use Buu\Modules\HaohaoceManager\Lib\K8sModel;
use Buu\Modules\HaohaoceManager\Lib\K8sView;
use Buu\Modules\HaohaoceManager\Lib\HhcService;
use Buu\Modules\HaohaoceManager\Lib\Podinfo;
use Buu\Modules\HaohaoceManager\Lib\Git;
use Buu\Modules\HaohaoceManager\Lib\Util;

class HaohaoceManagerController extends Controller
{
    
    public function __construct(){
        
        $this->podTypes = Util::read_conf();
    }

	public function index(Content $content, Request $request){

        $tab = new Tab();
        $tab->add('测试机列表', $this->_view_getPods(), true);
        foreach ($this->podTypes as $key => $value) {
            $tab->add('创建'.$value['name'], $this->_view_podform($key));
        }
        $content->row($tab);

        


        $content->row(function(Row $row){
            $row->column(7, new Box('容器连接方法' , '<p class="bg-warning">
            <h4>* 点击上方"复制连接容器命名"按钮 <img src="http://img.hhz1.cn/Op-imageShow/2d81f304l0150h400qyp0hb?iv=1
"/></h4>
            <h4>* 连接开发机：<b>ssh root@172.16.3.20</b></h4>
            <i>#默认网络密码</i>

            
            <h4>* 粘贴刚刚复制的命令，指定你要访问的容器名，回车！</h4>
            <p>示例：<br/>
kubectl exec -it hhc-fe-form-6-20210128140501-5fbdd4fccd-qdvtr -n hhc --container=<font color="red"><b>fe</b></font> -- /bin/bash
</p>
<p>
<i>上方红字就是container_name，有以下可选：</i>
<h4>后端环境</h4>
<li><b>nginx</b> <i>即openresty，需要修改nginx配置或查看访问日志可访问本container。（注：还包含fapi及静态文件）</i></li>
<li><b>php</b> <i>php-fpm专用，后端调试代码可用</i></li>
    <li style="padding-left:20px;"><i>可以使用 http://xhprof.qa??.haohaoce.com/index.php 查看xhprof</i></li>
<li><b>queue</b> <i>队列执行使用</i></li>
<li><b>fe</b> <i>前端项目</i></li>
<li><b>hyena</b> <i>go队列</i></li>
<li><b>mq</b> <i>rabbit mq</i></li>
    <li style="padding-left:20px;"><i>可以使用 http://rabbitmq.qa??.haohaoce.com/ 管理rabbitmq</i></li>

<h4>im环境</h4>
<li><b>im</b> <i>im项目</i></li>

<h4>go公用环境</h4>
<li><b>go-basic</b> <i>go公用环境</i></li>


<a href="https://confluence.haohaozhu.me/pages/viewpage.action?pageId=166269193"><h2>查看更多文档</h2></a>
            </p>'));
            $row->column(5, new Box('容器架构图及请求逻辑' , '
<p>
<img src="https://img.haohaozhu.cn/Op-imageShow/8279030a80fl0n900r8ipzi?iv=1" style="width:100%"/>
</p>
            '));
        });
        return $content
            ->header('测试机管理')
            ->breadcrumb(['text' => '测试机管理']);
	}

	public function showDesc(Content $content, Request $request , $podName,$svcName){
		$rs_pod = K8sModel::descPod($podName);
		$rs_pod = nl2br(str_replace(' ' , '&nbsp;&nbsp;' ,$rs_pod));
        $rs_svc = K8sModel::descSvc($svcName);
        $rs_svc = nl2br(str_replace(' ' , '&nbsp;&nbsp;' ,$rs_svc));

		$tab = new Tab();
        $tab->add('容器', $rs_pod, true);
        $tab->add('服务', $rs_svc, true);
        $content->row($tab);
        return $content
            ->header('测试机管理')
            ->breadcrumb(['text' => '测试机管理' , 'url' => '/haohaoceManager/index']);
	}
    public function testPod(Content $content, Request $request , $pod_id){
        $pod_info = HhcService::getPodInfo($pod_id , true);
        
        $cmd = $this->podTypes[$pod_info['pod_type']]['test_cmd'];
        $cmd = str_replace('{svc_external_ip}' , $pod_info['svc_external_ip'] , $cmd);
        $test = HhcService::testPod($cmd);

        $box = new Box('测试', '<h2>'.$cmd.'</h2><span>'.$test.'</span>');
        $content->row($box);
        return $content;
    }
    public function showProjects(Content $content, Request $request , $pod_id){
        $pod_info = HhcService::getPodInfo($pod_id , true);

        $containers = $this->podTypes[$pod_info['pod_type']]['containers'];
        
        $collapse = new Collapse();
            if($pod_info['pod_status'] != K8sModel::STATUS_RUNNING){
                $form_rs = '<h3>测试机初始化中，请稍等~</h3>';
            }


        foreach ($containers as $container_name => $container_info) {
            $projects_str = K8sModel::execByPodname($pod_info['pod_name'] , $container_name , 'ls /data/wwwroot');
            $projects = array_filter(explode("\n" , $projects_str));

            $tab = new Tab();
            $is_first = true;
            foreach ($projects as $project_dir) {
                $tab->add($project_dir, '<iframe width="100%" height="500px" frameborder=no scrolling="no" '.($is_first ? 'src': 'nsrc').'="/admin/haohaoceManager/switchProjectBranch/'.$pod_id.'/'.$container_name.'/'.$project_dir.'"></iframe>');
                $is_first = false;
            }
            $collapse->add($container_info['desc'], $tab);            
        }
        $content->row($collapse);
        
        
        $box = new Box('', '<iframe id="create_iframe" name="create_iframe" width="100%" height="200px" frameborder=no>sdf</iframe>');
        $content->row($box);

        $script = <<<script
        $('form').attr('target','create_iframe');
        /* 点击tab时，动态显示iframe */
        $('a').click(function(){
            target=$(this).attr('href');
            if(target.substr(0,5) == '#tab_'){
                iframe_id=target.substr(1);
                iframe=$('#'+iframe_id).children("iframe:first");
                if(typeof iframe.attr('src') == 'undefined'){
                    iframe.attr('src' , iframe.attr('nsrc'));
                }
            }

        });
script;
        Admin::script($script);


        $admin_name = Admin::user()->find($pod_info['admin_id'])->name;
        return $content
            ->header($admin_name.'--'.$pod_info['desc'])
            ->breadcrumb(['text' => '测试机管理' , 'url' => '/haohaoceManager/index']);
    }
    
    public function switchProjectBranch(\App\Admin\Extensions\WorkContent $content, Request $request , $pod_id ,$container_name, $project_dir){
        $pod_info = HhcService::getPodInfo($pod_id , true);
        if($pod_info['pod_status']==K8sModel::STATUS_RUNNING){
            $current_branch = HhcService::getCurrentBranch($pod_id ,$container_name, $project_dir);
            $msg = '当前分支：'.$current_branch;
        }else if ($pod_info['pod_status'] == K8sModel::STATUS_CRASHLOOPBACKOFF){
            $msg = '<p class="text-danger">容器错误！</p>';
        }else{
            $msg = '测试环境创建中，请选择分支，后续会自动生效';
        }

        
        $rs = K8sModel::execByPodname($pod_info['pod_name'] , $container_name , 'cd /data/wwwroot/'.$project_dir.';git fetch;git branch -a');
        $branchs = explode("\n" , $rs);
        unset($branchs[0]);
        unset($branchs[0]);

        $branchs = array_combine($branchs, $branchs);
        $form = new Form();
        $form->html('<h3>'.$msg.'</h3>');
        $form->select('branch' , '分支')->options($branchs)->default($current_branch);
        $form->action('/admin/haohaoceManager/do_switchBranch/'.$pod_id.'/'.$container_name.'/'.$project_dir.'/');
        return $content
            ->body($form->render());
    }
    public function do_switchBranch(Content $content, Request $request , $pod_id ,$container_name, $project_dir){
        $branch = $request->input('branch');
        $rs = HhcService::switchBranch($pod_id ,$container_name , $project_dir , $branch);
        if($rs === true){
            admin_toastr('切换成功', 'success', ['timeOut' => 5000]);
            return redirect('/admin/haohaoceManager/switchProjectBranch/'.$pod_id.'/'.$container_name.'/'.$project_dir.'')->with(compact('success'));
        }else{
            die($rs);
        }
    }
    public function do_switchAllBranch(Content $content, Request $request , $pod_id ){
        $branch = $request->input('branch');
        $pod_info = HhcService::getPodInfo($pod_id , true);
        
        $containers = $this->podTypes[$pod_info['pod_type']]['containers'];

        $is_ok = true;
        foreach ($containers as $container_name => $container_info) {
            $rs = HhcService::switchAllBranch($pod_id , $pod_info['pod_name'] , $container_name , $container_info['code_dir'] , $branch);
            if($rs !== true){
                $is_ok = false;
            }
        }
        if($is_ok){
            K8sView::time_to_jump('/admin/haohaoceManager/showProjects/'.$pod_id.'/'.$container_name.'/');
            // admin_toastr('切换成功', 'success', ['timeOut' => 5000]);
            // return redirect('/admin/haohaoceManager/showProjects/'.$pod_id.'/'.$container_name.'/'.$project_dir.'')->with(compact('success'));
        }
    }
    public function do_pullCode(Content $content, Request $request , $pod_id){
        $pod_info = HhcService::getPodInfo($pod_id);
        $containers = $this->podTypes[$pod_info['pod_type']]['containers'];
        //先删除所有代码重新copy
        foreach ($containers as $container_name => $info) {
            $rs = HhcService::pullCode($pod_info['pod_name'] , $container_name);
        }

        admin_toastr('已完成', 'success', ['timeOut' => 5000]);
        return redirect('/admin/haohaoceManager/index/')->with(compact('success'));
    }
    /**
     * 绑定域名ip
     * @param  Content $content [description]
     * @param  Request $request [description]
     * @param  [type]  $pod_id  [description]
     * @return [type]           [description]
     */
    public function do_bindDomain(Content $content, Request $request , $pod_id){
        
        HhcService::bindDomain($pod_id);
        HhcService::add_slb_forward_rule();
        
        admin_toastr('保存成功,1分钟中后可用', 'success', ['timeOut' => 5000]);
        return redirect('/admin/haohaoceManager/index/')->with(compact('success'));
    }

    public function do_create(Content $content, Request $request , $pod_type){
        $admin_id = Admin::user()->id;
        $admin_name = Admin::user()->name;
        $admin_email = Admin::user()->email;
        
        $desc = $request->input('desc');
        $expire = $request->input('expire');
        $pod_resource = $request->input('pod_resource');
        $domain_suffix = $request->input('domain_suffix');
        $auto_pull = $request->input('auto_pull') == 'on' ? 1 : 0;

        //生成一个pod_id
        $pod_id = HhcService::init_pod_id($admin_id);

        //配置文件模板路径
        $yaml_name = $this->podTypes[$pod_type]['hhc_k8s_yaml'];
        $svc_yaml_name = $this->podTypes[$pod_type]['hhc_k8s_svc_yaml'];

        //环境变量
        $env = [
            'owner' => $admin_name, //主人 用于存放日志
            'wx_id' => Util::name_to_wx_at($admin_name), //email 用于通知
            'pod_id' => $pod_id,    //pod_id
            'domain_suffix' => $domain_suffix,    //pod_id
            'auto_pull' => $auto_pull,    //
        ];
        
        if(!empty($this->podTypes[$pod_type]['env'])){
            foreach ($this->podTypes[$pod_type]['env'] as $key => $value) {
                $env[$key] = $request->input('env_'.$key);
            }
        }

        $pod_info = Podinfo::formatPodInfo(
            $pod_id ,
            $admin_id,
            $admin_name,
            $admin_email,
            $pod_type,
            $pod_resource,
            $domain_suffix,
            $expire,
            $desc,
            $env,
            Podinfo::STATUS_UNREADY
        );
        $ext = array();

        foreach ($this->podTypes[$pod_type]['resource'][$pod_resource] as $ext_type => $row) {
            foreach ($row as $ext_name => $value) {
                $ext[$ext_type.'_'.$ext_name] = $value;
            }
        }
        $rs = HhcService::createPod($yaml_name,$svc_yaml_name , $pod_id , $pod_info , $ext);
        if($rs){
            K8sView::time_to_jump('/admin/haohaoceManager/index');
        }
    }
    public function do_deletePod(Content $content, Request $request , $pod_id){
        $admin_name = Admin::user()->name;

        
    
        $rs = HhcService::deletePod($pod_id);
        if($rs){
            K8sView::time_to_jump('/admin/haohaoceManager/index');
        }
    }
    public function do_delay(Content $content, Request $request , $pod_id){
        $rs = HhcService::delay_expire_by_podid($pod_id);
        
        admin_toastr('保存成功', 'success', ['timeOut' => 5000]);
        return redirect('/admin/haohaoceManager/index/')->with(compact('success'));
    }

	private function _view_getPods(){

		$admin_name = Admin::user()->name;
        $is_administrator = Admin::user()->isAdministrator();
		
        $rs = HhcService::getPods();
        $list = $rs['podInfos'];
		$gridModel = new pGridDataModel($list);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel , $admin_name , $is_administrator) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableFilter();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
                $grid->disablePagination();

                $grid->column("pod_id", 'pod_name(pod_id)')->display(function(){
                    return '<b>'.$this->pod_name.'</b>
                    <br/>(<i>'.$this->pod_id.'</i>)';
                });
                $grid->column("admin_id", '创建者')->display(function(){
                    return Admin::user()->find($this->admin_id)->name;
                });
                
                $grid->column("pod_type", '类型');
                $grid->column("pod_resource", '配置');
                $grid->column("domain_suffix", '域名后缀')->display(function(){
                    return '*.qa<span class="label label-success">'.$this->domain_suffix.'</span>.haohaoce.com';
                });
                $grid->column("desc", '用途');
                $grid->column("time", '时间')->display(function(){
                    return '创建时间：'.K8sView::timeFormat($this->create_time).'<br/>结束使用时间：'.$this->expire;
                });
                $grid->column("pod_status", '容器状态')->display(function(){
                	return K8sView::statusFormat($this->pod_status);
                });
                $grid->column("svc_external_ip", 'ip地址');
                $grid->actions(function (Grid\Displayers\Actions $actions) use ($admin_name , $is_administrator) {
                    $actions->disableDelete();
                    $actions->disableEdit();

                    $enable_bind_ip = false;
                    if(preg_match('/^[0-9\.]+$/' , $actions->row['svc_external_ip'])){
                        $enable_bind_ip = true;
                    }

                    $actions->append('<a href="/admin/haohaoceManager/showDesc/'.$actions->row['pod_name'].'/'.$actions->row['svc_name'].'" class="fa fa-search btn btn-default">详情</a>');
                    $actions->append('<a href="/admin/haohaoceManager/testPod/'.$actions->row['pod_id'].'/" class="fa fa-magic btn btn-default"'.($actions->row['pod_status'] != 'Running' ? ' disabled="disabled"':'').'>测试</a>');
                    $actions->append('<a href="/admin/haohaoceManager/do_bindDomain/'.$actions->row['pod_id'].'/" target="create_iframe" class="fa fa-plane btn btn-default"'.($enable_bind_ip ? '':' disabled="disabled"').'>绑定ip</a>');

                    $actions->append('<br/>');
                    
                    $actions->append('<a href="/admin/haohaoceManager/showProjects/'.$actions->row['pod_id'].'" class="fa fa-random btn btn-default">切分支</a>');
                    $actions->append('<a href="/admin/haohaoceManager/do_pullCode/'.$actions->row['pod_id'].'/" class="fa fa-refresh btn btn-default"'.($actions->row['pod_status'] != 'Running' ? ' disabled="disabled"':'').'>更新代码</a>');
                    $actions->append('<a href="#" onclick="if(confirm(\'确认要释放测试机嘛？\')){window.location.href=\'/admin/haohaoceManager/do_deletePod/'.$actions->row['pod_id'].'\'}" class="fa fa-remove btn btn-danger">释放</a>');

                    $actions->append('<br/>');

                    $actions->append('<a href="/webconsole.php?owner='.$actions->row['admin_name'].'&pod_id='.$actions->row['pod_id'].'" target="_blank" class="fa fa-search btn btn-default">查看日志</a>');
                    $actions->append('<a href="javascript:return false;" class="fa fa-copy btn btn-info btn_copy_podname" pod_name="'.$actions->row['pod_name'].'" data-toggle="popover" data-delay="{\'hide\':300}" data-content="已复制！">复制连接容器命令</a>');
                    $actions->append('<br/>');

                    $actions->append('<a href="/admin/haohaoceManager/do_delay/'.$actions->row['pod_id'].'/" target="create_iframe" class="fa fa-clock-o btn btn-default">多用2小时</a>');

                    
                });
            });
        $script = <<<script
    function copy(text) {
    var textareaEl = document.createElement('textarea');
    textareaEl.setAttribute('readonly', 'readonly'); // 防止手机上弹出软键盘
    textareaEl.value = text;
    document.body.appendChild(textareaEl);
    textareaEl.select();
    var res = document.execCommand('copy');
    document.body.removeChild(textareaEl);
    console.log("复制成功");
    return true;
}
    $('.btn_copy_podname').click(function(){
        cmd="kubectl exec -it "+$(this).attr('pod_name')+" -n hhc --container=php -- /bin/bash"
        copy(cmd);
        $(this).popover()
        target=$(this)
        setTimeout(
            function(){
                target.popover('hide')
            }
            , 1000 )
        })
script;
        Admin::script($script);

        return $gridList->render();
	}
    private function _view_podform($pod_type , $pod_info = null){
        $pod_resource = array_keys($this->podTypes[$pod_type]['resource']);
        $pod_resource = array_combine($pod_resource , $pod_resource);
        $pod_env = $this->podTypes[$pod_type]['env'];


        $usedDomainSuffixes = HhcService::getUsedDomainSuffix();
        list($suffix_start_num , $suffix_over_num) = HhcService::get_suffix_start_end_num();
        $domain_suffix = array();
        for($i = $suffix_start_num;$i<$suffix_over_num;$i++){
            if(false === array_search($i , $usedDomainSuffixes)){
                $domain_suffix[] = $i;
            }
        }
        $domain_suffix = array_combine($domain_suffix , $domain_suffix);

        $form = new Form($pod_info);
        if(!empty($this->podTypes[$pod_type]['desc'])){
            $form->html('<p class="bg-warning">'.$this->podTypes[$pod_type]['desc'].'</p>');
        }
        $form->text('desc' , '用途描述');
        $form->radio('pod_resource' ,'配置')->options( $pod_resource);
        $form->select('domain_suffix','域名后缀')
        ->options($domain_suffix)
        ->help('可使用如 yapi.qa<span class="label label-success">11</span>.haohaoce.com 访问');
        // $form->datetime('expire' , '结束使用时间')->format('YYYY-MM-DD HH:mm:ss');
        $expire_list = [
            date('Y-m-d H:i:s' , time()+1*60*60) => '1小时',
            date('Y-m-d H:i:s' , time()+3*60*60) => '3小时',
            date('Y-m-d 20:59:59' , time()) => '今天 （到晚上9点）',
        ];
        $form->radio('expire' ,'使用时长')->options( $expire_list)->help("过期自动释放");
        
        if(!empty($pod_env)){
            foreach ($pod_env as $key => $value) {
                $env = $form->text('env_'.$key , $value['name']);
                if($value['desc']){
                    $env->help($value['desc']);
                }
                if($value['default']){
                    $env->default($value['default']);
                }
            }
        }


        $states = [
            '1'  => ['value' => 1, 'text' => '打开', 'color' => 'success'],
            '0' => ['value' => 0, 'text' => '关闭', 'color' => 'danger'],
        ];
        $form->switch('auto_pull' , '开启代码自动更新？')->states($states);

        $form->action('/admin/haohaoceManager/do_create/'.$pod_type.'/');



        return $form->render();
    }
    static private function _run_cmd($cmd){
        $fp = popen($cmd , 'r');
        while ($str = fread($fp , 4096)) {
            $rs.=$str;
        };
        return $rs;
    }
}